package cn.itcast.nems.enrol.service.impl;

import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.ic.common.exception.v2.bean.BizStatusEnum;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 快捷报名相关配置
 * author liyong
 * create: 2024-04-14 11:36:11
 **/
@RefreshScope
@Component
@ConfigurationProperties(prefix = "enrol.quick")
@Data
public class EnrolQuickConfig {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private volatile List<ActivityConfig> activityConfigs;

    // private volatile Map<String, ActivityConfig> activityConfigMap;

    // @Value("${enrol.quick.activityConfigs}")
    // public void setActivityConfigs(List<ActivityConfig> activityConfigs) {
    //     logger.info("activityConfigs change {}", activityConfigs);
    //     this.activityConfigs = activityConfigs;
    //     final Map<String, ActivityConfig> newMap = activityConfigs.stream().collect(Collectors.toMap(ActivityConfig::getActivityCode, Function.identity()));
    //     logger.info("activityConfigs from '{}' change to '{}'", this.activityConfigMap, newMap);
    //     this.activityConfigMap = newMap;
    // }
    //
    // public List<ActivityConfig> getActivityConfigs() {
    //     return activityConfigs;
    // }
    //
    // public ActivityConfig findActivityConfig(String activityCode) {
    //     return this.activityConfigMap.get(activityCode);
    // }

    public ActivityConfig findActivityConfig(String activityCode) {
        return this.activityConfigs.stream().filter(a -> a.getActivityCode().equals(activityCode)).findAny().map(a -> {
            if (a.getState() != 0) {
                String msg = a.getState() == -1 ? "还未开始" : "已经结束";
                BizExceptionProducer.throwBadRequest(BizStatusEnum.BAD_REQUEST.name(), "活动'%s'%s", activityCode, msg);
            }
            return a;
        }).orElseThrow(BizExceptionProducer.badRequest("活动代码'%s'没有找到", activityCode));
    }
}
